package com.hemaapp.yjnh.activity;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.hemaapp.BaseConfig;
import com.hemaapp.yjnh.alipay.Result;
import com.hemaapp.yjnh.bean.AlipayTrade;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.UnionTrade;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.bean.WeixinTrade;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;
import com.unionpay.uppay.PayActivity;

/**
 * 余额充值
 * */
public class ChargeMoneyActivity extends BaseActivity implements OnClickListener{

	private ImageButton left;
	private Button right;
	private TextView title;

	private EditText edit_score;//输入充值金额

	private LinearLayout ll_ali;
	private LinearLayout ll_union;
	private LinearLayout ll_wechat;
	private RadioButton rbtn_ali;
	private RadioButton rbtn_union;
	private RadioButton rbtn_wechat;

	private ArrayList<RadioButton> rbtns = new ArrayList<RadioButton>();// 存储3中支付方式的RadioButton

	private Button button;//确定按钮
	private String money;// 充值金额

	IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
	private int type = 1;//1账户充值，2粮票充值
	private User user;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_chargemoney);
		super.onCreate(savedInstanceState);
		user = getApplicationContext().getUser();
		if (user == null) {
            Intent intent = new Intent(mContext, LoginActivity.class);
            startActivity(intent);
            finish();
        }
		msgApi.registerApp(BaseConfig.APPID_WEIXIN);
		rbtns.add(rbtn_ali);
		rbtns.add(rbtn_union);
		rbtns.add(rbtn_wechat);
	}

	@Override
	protected void onResume() {
		String weixinpay = XtomSharedPreferencesUtil.get(mContext,"weixinpay");
		if( weixinpay != null && (weixinpay.equals("1"))){//说明是从微信支付完成后返回
			XtomSharedPreferencesUtil.save(mContext,"weixinpay","0");
			String status = XtomSharedPreferencesUtil.get(mContext,"status");
			if("-1".equals(status)){  //支付失败
				showTextDialog("支付失败!");
			}else if("-2".equals(status)){ //支付取消
				showTextDialog("您取消了支付!");
			}else{
				showTextDialog("支付成功");
                EventBusMsg eventBusMsg = new EventBusMsg();
                eventBusMsg.setType(EventBusConfig.UPDATE_INFO);
                EventBus.getDefault().post(eventBusMsg);
                title.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
			}
		}
		super.onResume();
	}


	@Override
	protected boolean onKeyBack() {
		finish();
		return true;
	}

	@Override
	protected void findView() {
        left = (ImageButton) findViewById(R.id.title_left_btn);
        title = (TextView) findViewById(R.id.title_text);
        right = (Button) findViewById(R.id.title_right_btn);


		edit_score = (EditText) findViewById(R.id.total_fee);

		//5中支付方式
		ll_ali = (LinearLayout) findViewById(R.id.ll_ali);
		ll_union = (LinearLayout) findViewById(R.id.ll_union);
		ll_wechat = (LinearLayout) findViewById(R.id.ll_wechat);
		rbtn_ali = (RadioButton) findViewById(R.id.rbtn_alipay);
		rbtn_union = (RadioButton) findViewById(R.id.rbtn_union);
		rbtn_wechat = (RadioButton) findViewById(R.id.rbtn_wechat);

		button = (Button) findViewById(R.id.button);
	}

	@Override
	protected void getExras() {
	    type = mIntent.getIntExtra("type", 1);
	}

	@SuppressLint("NewApi") @Override
	protected void setListener() {
		title.setText("充值");
		right.setVisibility(View.INVISIBLE);
		left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		//3中支付方式
		ll_ali.setOnClickListener(this);
		ll_union.setOnClickListener(this);
		ll_wechat.setOnClickListener(this);

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				money = edit_score.getText().toString().trim();
				if (isNull(money)) {
					XtomToastUtil.showShortToast(mContext, "请填写要充值的金额");
					return;
				}
                if (money.equals("0")) {
                    XtomToastUtil.showShortToast(mContext, "不能充值0元");
                    return;
                }
                if (rbtn_ali.isChecked()) { // 支付宝支付
                    alipayTrade();
                } else if (rbtn_union.isChecked()) { // 银联支付
                    uppayTrade();
                } else if (rbtn_wechat.isChecked()) { // 微信支付
                    weixinTrade();
                } else {
                    XtomToastUtil.showShortToast(mContext, "请选择支付方式");
                }
			}
		});
		edit_score.addTextChangedListener(new TextWatcher() {
			private boolean isChanged = false;
			private int length = 2;// 小数点后的2位

			@Override
			public void onTextChanged(CharSequence s, int start,
					int before, int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start,
					int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (isChanged) {// ----->如果字符未改变则返回
					return;
				}
				String str = s.toString();
				String dotBefore = "";// 小数点前的整数部分
				String dotAfter = "";// 小数部分
				isChanged = true;

				int dotIndex = str.indexOf(".");// 小数点的位置
				if (dotIndex > 0) {// 有小数点
					dotBefore = str.substring(0, dotIndex);
					dotAfter = str.substring(dotIndex + 1);
				} else {// 没有小数点
					dotBefore = str;
				}
				// 删除整数部分开头的0
				while (dotBefore.length() > 1 && dotBefore.startsWith("0")) {
					dotBefore = dotBefore.substring(1);
				}
//				if (dotBefore.length() != 1) {
//					while (dotBefore.startsWith("0")) {
//						dotBefore = dotBefore.substring(1);
//					}
//				}
				// 删除小数点后两位之后的数字
				if (dotAfter.length() > 2) {
					dotAfter = dotAfter.substring(0, 2);
				}
				// 重新组合字符串
				if (dotIndex > 0) {// 有小数点
					str = dotBefore + "." + dotAfter;
				} else if (dotIndex == 0) {// 如果输入的内容以小数点开头，就去掉小数点
					str = "";
				} else {// 没有小数点
					str = dotBefore;
				}
				edit_score.setText(str);
				// 设置光标到最后
				edit_score.setSelection(edit_score.length());
				isChanged = false;
			}
		});
	}

	// 银联
	private void uppayTrade() {
        String keytype = "1";
        if (type == 2) {//粮票
          keytype = "3";
        }
        getNetWorker().unionpay(user.getToken(), "2", keytype, "0", money, "0", ""); //生产环境
	}

	// 支付宝
	private void alipayTrade() {
		String keytype = "1";
		if (type == 2) {//粮票
	          keytype = "3";
        }
        getNetWorker().alipay(user.getToken(), "1", keytype, "0", money, "0", ""); //生产环境
	}
	
	// 微信
	private void weixinTrade() {
        String keytype = "1";
        if (type == 2) {//粮票
            keytype = "3";
        }
		getNetWorker().weixinpay(user.getToken(), "3", keytype, "0", money, "0", "");
	}

	private void goWeixin(WeixinTrade trade) {
		msgApi.registerApp(BaseConfig.APPID_WEIXIN);

		PayReq request = new PayReq();
		request.appId = trade.getAppid();
		request.partnerId = trade.getPartnerid();
		request.prepayId = trade.getPrepayid();
		request.packageValue = trade.getPackageValue();
		request.nonceStr = trade.getNoncestr();
		request.timeStamp = trade.getTimestamp();
		request.sign = trade.getSign();
		msgApi.sendReq(request);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		/*************************************************
		 * 处理银联手机支付控件返回的支付结果
		 ************************************************/
		if (data == null) {
			return;
		}

		String msg = "";
		/*
		 * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
		 */
		String str = data.getExtras().getString("pay_result");
		if (str.equalsIgnoreCase("success")) {
			msg = "支付成功！";
			showTextDialog(msg);
			EventBusMsg eventBusMsg = new EventBusMsg();
			eventBusMsg.setType(EventBusConfig.UPDATE_INFO);
			EventBus.getDefault().post(eventBusMsg);
			title.postDelayed(new Runnable() {

				@Override
				public void run() {
					finish();
				}
			}, 1000);
		} else if (str.equalsIgnoreCase("fail")) {
			msg = "支付失败！";
			showTextDialog(msg);
		} else if (str.equalsIgnoreCase("cancel")) {
			msg = "您取消了支付";
			showTextDialog(msg);
		}
	}


	@Override
	protected void callBeforeDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case ALIPAY:
        case WEIXINPAY:
		case UNIONPAY:
			showProgressDialog("请稍候");
			break;
		default:
			break;
		}
	}

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case ALIPAY:
		case UNIONPAY:
        case WEIXINPAY:
			cancelProgressDialog();
			break;
		default:
			break;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case ALIPAY:
			HemaArrayResult<AlipayTrade> aResult = (HemaArrayResult<AlipayTrade>) baseResult;
			AlipayTrade trade = aResult.getObjects().get(0);
			String orderInfo = trade.getAlipaysign();
			new AlipayThread(orderInfo).start();
			break;
		case UNIONPAY:
			HemaArrayResult<UnionTrade> uResult = (HemaArrayResult<UnionTrade>) baseResult;
			UnionTrade uTrade = uResult.getObjects().get(0);
			String uInfo = uTrade.getTn();
			UPPayAssistEx.startPayByJAR(mContext, PayActivity.class, null, null,
					uInfo, BaseConfig.UNIONPAY_TESTMODE);
			break;
		case WEIXINPAY:
			@SuppressWarnings("unchecked")
			HemaArrayResult<WeixinTrade> wResult = (HemaArrayResult<WeixinTrade>) baseResult;
			WeixinTrade wTrade = wResult.getObjects().get(0);
			goWeixin(wTrade);
			break;
		default:
			break;
		}
	}

	private class AlipayThread extends Thread {
		String orderInfo;
		AlipayHandler alipayHandler;

		public AlipayThread(String orderInfo) {
			this.orderInfo = orderInfo;
			alipayHandler = new AlipayHandler(ChargeMoneyActivity.this, title, money);
		}

		@Override
		public void run() {
			// 构造PayTask 对象
			PayTask alipay = new PayTask(ChargeMoneyActivity.this);
			String result = alipay.pay(orderInfo);
			
			log_i("result = " + result);
			Message msg = new Message();
			msg.obj = result;
			alipayHandler.sendMessage(msg);
		}
	}

	//阿里的支付操作完成后的回调
	private static class AlipayHandler extends Handler {
		ChargeMoneyActivity activity;
		View view;
		String total_fee;

		public AlipayHandler(ChargeMoneyActivity activity, View view, String total_fee) {
			this.activity = activity;
			this.view = view;
			this.total_fee = total_fee;
		}

		public void handleMessage(android.os.Message msg) {
			Result result = new Result((String) msg.obj);
			int staus = result.getResultStatus();
			switch (staus) {
			case 9000:
				activity.showTextDialog("恭喜\n支付成功");
				User user = BaseApplication.getInstance().getUser();
				String oldFee = user.getFeeaccount();
				Double newFee = Double.valueOf(oldFee) + Double.valueOf(total_fee);
				user.setFeeaccount(newFee.toString());
				BaseApplication.getInstance().setUser(user); //修改本地用户余额
				EventBusMsg eventBusMsg = new EventBusMsg();
				eventBusMsg.setType(EventBusConfig.UPDATE_INFO);
				EventBus.getDefault().post(eventBusMsg);
				view.postDelayed(new Runnable() {

					@Override
					public void run() {
						activity.finish();
					}
				}, 1000);
				break;
			default:
				activity.showTextDialog(result.getResult());
				break;
			}
		};
	}

	@Override
	protected void callBackForServerFailed(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case ALIPAY:
		case UNIONPAY:
        case WEIXINPAY:
			XtomToastUtil.showShortToast(mContext, "充值失败,"+baseResult.getMsg());
			break;
		}
	}

	@Override
	protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case ALIPAY:
		case UNIONPAY:
        case WEIXINPAY:
			XtomToastUtil.showShortToast(mContext, "充值失败, 请稍后再试");
			break;
		default:
			break;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ll_ali:
			setRbtn(rbtn_ali);
			break;
		case R.id.ll_union:
			setRbtn(rbtn_union);
			break;
		case R.id.ll_wechat:
			setRbtn(rbtn_wechat);
			break;
		default:
			break;
		}
	}
	
	private void setRbtn(RadioButton rbtn) {
		for (RadioButton rb : rbtns) {
			if (rbtn.equals(rb)) {
				rb.setChecked(true);
			} else {
				rb.setChecked(false);
			}
		}
	}

}
